package com.cloudfun.campusshare.device.protocol.decoder;


import java.util.Map;
import java.util.function.BiConsumer;

/**
 * Created by Huqin on 2020/1/3
 */
public class BitSwitchFieldDecoder<T> extends AbstractFieldDecoder<T> {

    private final Map<Integer, BiConsumer<T, Boolean>> fieldSetterMap;

    public BitSwitchFieldDecoder(int start, int length, Map<Integer, BiConsumer<T, Boolean>> fieldSetterMap) {
        super(start, length);
        this.fieldSetterMap = fieldSetterMap;
    }

    @Override
    public void decode(byte[] data, T obj) {
        byte num = data[data.length - 1];
        for (Map.Entry<Integer, BiConsumer<T, Boolean>> entry : fieldSetterMap.entrySet()) {
            int pos = entry.getKey();
            int expected = 1 << pos;
            int actual = expected & num;
            boolean bitSwitch = expected == actual;
            if (bitSwitch) {
                entry.getValue().accept(obj, true);
            }
        }
    }
}
